from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required

from s_te.utils import delete_slug
from t_ch.models import Technology
from t_ch.admin.forms import TechnologyForm

@staff_member_required
def main(request, template_name="t_ch/admin/main.html"):
    """
    Technology admin, listing all technologies
    """
    technologies = Technology.objects.all()
    return render_to_response(template_name, {'technologies':technologies, 'nav_page': 't_ch_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="t_ch/admin/create.html"):
    """
    Create a new technology
    """
    if request.POST:
        form = TechnologyForm(request.POST)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Technology created.")
            return HttpResponseRedirect(reverse('t_ch_admin_main'))
    else:
        form = TechnologyForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="t_ch/admin/edit.html"):
    """
    Edit an existing technology
    """
    technology = get_object_or_404(Technology, slug=slug)
    if request.POST:
        form = TechnologyForm(request.POST, instance=technology)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Technology saved.")
            return HttpResponseRedirect(reverse('t_ch_admin_main'))
    else:
        form = TechnologyForm(instance=technology)
    return render_to_response(template_name, {'technology':technology, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing technology
    """
    delete_slug(Technology, request)
    request.user.message_set.create(message="Technology deleted.")
    return HttpResponseRedirect(reverse('t_ch_admin_main'))
